#include "keys.h"



void sh_key::keyPressEvent ( QKeyEvent * event ){
this->setText(QString("%1").arg(event->nativeVirtualKey()));
event->ignore();
}

keys::keys(QWidget *parent) :
    QDialog(parent)
{

QScrollArea *area=new QScrollArea(this);
QVBoxLayout *lay=new QVBoxLayout(this);
lay->addWidget(area);
QWidget *wg=new QWidget();
area->setWidget(wg);
wg->setMinimumSize(600,1200);
QGridLayout *grid=new QGridLayout(wg);
wg->show();
area->show();
grid->setHorizontalSpacing(25);
grid->setVerticalSpacing(25);

QStringList ks=QStringList()<<tr("Left")<<tr("Right")<<tr("Up")
                            <<tr("Down")<<tr("o")<<tr("x")<<tr("triangle")
                            <<tr("square")<<tr("Select")<<tr("Start")
                            <<tr("L1")<<tr("R1")<<tr("L2")<<tr("R2")<<tr("Quit")
                            <<tr("Up+Left")<<tr("Up+Right")
                            <<tr("Down+Left")<<tr("Down+Right")
                            <<tr("Save")<<tr("Load");


grid->setColumnStretch(1, 10);
grid->setColumnStretch(2, 20);

// load current

QFile file("/opt/psx4m/keys");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
    QMessageBox msg;
    msg.setText(tr("Couldn't open previous key config"));
    msg.exec();
}

int o=0;
     QTextStream in(&file);
     while ((o<21)) {
         QString line="0";
         if (!in.atEnd())
         line = in.readLine();

         QLabel *lbl=new QLabel(ks.at(o),wg);
         grid->addWidget(lbl,o,1,1,1);

         nkey[o]=new sh_key();
         nkey[o]->setParent(wg);
         nkey[o]->setMinimumSize(150,60);

         grid->addWidget(nkey[o],o,0,1,1);
         grid->setRowMinimumHeight(o,80);
         nkey[o]->show();
         nkey[o]->setText(line.trimmed());
         o++;
     }


     QPushButton *but=new QPushButton(tr("Save"),this);
     grid->addWidget(but,21,0,2,2);
     connect(but,SIGNAL(clicked()),this,SLOT(save()));

}

void keys::save(){
QString sv="";
qDebug("1");
for (int i=0;i<=20;i++)
    sv=sv+QString("%1\n").arg(nkey[i]->text());
qDebug("2");

QFile file("/opt/psx4m/keys");
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)){
    QMessageBox msg;
    msg.setText("Somethings goes wrong, check permission to keys file");
    msg.exec();
    return;}

     QTextStream out(&file);
     out <<sv;
qDebug("3");
this->accept();
this->close();
}

void keys::hk(QString txt){
    QLineEdit *action = qobject_cast<QLineEdit *>(sender());
    action->setText(QString("%1").arg((int)QChar(txt.at(0)).toAscii() ));
    action->setCursorPosition(0);

}

keys::~keys()
{

}
